package funcSless

import (
	"time"

	"gitee.com/wchpub/fnsvr"
	"github.com/redis/go-redis/v9"
)

// 玩家跨进程锁
type playerLock struct {
	//被锁定的玩家id队列
	playerIds map[string]string
	redis     *redis.Client
}

// 初始化一个跨进程玩家锁实例
func initPlayerLock(redis *redis.Client, inst *playerLock) {
	inst.playerIds = make(map[string]string)
	inst.redis = redis
}

// 生成角色锁名字
func generatePlayerLockName(plyId string) string {
	return "playerLock:" + plyId
}

// 锁定玩家数据
// maxWait 最大等待时长
func (m *playerLock) lock(maxWait time.Duration, plyIds ...string) error {
	for _, id := range plyIds {
		_, exist := m.playerIds[id]
		if exist {
			continue
		}

		//执行锁定操作
		lockKey := generatePlayerLockName(id)
		lockValue, err := fnsvr.CrossProcessLockWithWait(m.redis, lockKey, maxWait*2, maxWait)
		if err != nil {
			return err
		}

		//加入到已锁定集合
		m.playerIds[id] = lockValue
	}
	return nil
}

// 释放玩家锁
func (m *playerLock) unLock() {
	for id, lockValue := range m.playerIds {
		lockKey := generatePlayerLockName(id)
		err := fnsvr.CrossProcessReleaseLock(m.redis, lockKey, lockValue)
		if err != nil {
			fnsvr.Log().Error("playerLock.UnLock", "err", err)
		}
	}
	m.playerIds = make(map[string]string)
}
